<?php
class model_weixin extends model_base{
	
	public static $postDataStr = '';
    public static $postDataObj = '';
    public static $toUserName = '';
    public static $fromUserName = '';
    public static $msgType = '';
    public static $eventKey = '';
    public static $access_token = '';
    private static $memcache = '';
    /**
     * @info 检测消息类型
     * @author Jackie Yang
     */
    public static function checkType(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        framework_static_function::write_log($postStr,'weixin');
        if(!empty($postStr)){
            self::$postDataStr = $postStr;
            self::$postDataObj =simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            self::$fromUserName = self::$postDataObj -> FromUserName;
            self::$toUserName = self::$postDataObj -> ToUserName;
            self::$msgType = self::$postDataObj -> MsgType;
            self::$eventKey = self::$postDataObj -> EventKey;
            return self::$msgType;
        }else{
            echo "";
            exit;
        }
    }
    
    /**
     * @info 根据userAgent判断是否是微信浏览器过来
     * @author Jackie Yang
     * @date 20140714
     */
    public static function is_weixin(){
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== FALSE){
            return TRUE;
        }
        return FALSE;
    }
    
    /**
     * @info 判断ip是否在白名单   设置菜单、获取关注列表等接口访问
     * @author Jackie Yang
     * @date 20140712
     */
    public static function white_ip($ip){
        $client_ip = framework_static_base::real_ip();
        $white_ip = $ip;
        $white_ip = explode('|', $white_ip);
        if(!in_array($client_ip,$white_ip)){
            echo $client_ip;
            return FALSE;
        }
        return TRUE;
    }
    
    /**
     * @info 获取全局的access_token
     * @author Jackie Yang
     */
    public static function get_access_token_old(){
        if(!empty(self::$access_token)){
            return self::$access_token;
        }
        $tempath = APP_PATH . "/data";
        if(!is_dir($tempath)) {
            $res = mkdir($tempath, 0775, true);
            if(!$res){
                exit('日志目录没有权限');
            }
        }
        $info = file_get_contents($tempath . '/access_token.conf');
        if($info != FALSE ){
            $arr = json_decode($info);
            $arr = get_object_vars($arr);
            if(!empty($arr['access_token']) && ($arr['time'] > time())){
                self::$access_token = $arr['access_token'];
                return $arr['access_token'];
            }
        }
        $info = self::get_access_token_by_weixin();
        self::$access_token = $info;
        return $info;
        //framework_static_function::write_log($info,'weixin');
    }
    
    /**
     * @info 通过读取磁盘文件获取access_token
     * @author Jackie Yang
     * @date 20140622
     */
    public static function get_access_token(){
    	$access_token = '';
    	$accessValue = file_get_contents(ACCESSTOKEN_FILE);
        if(!empty($accessValue)){
            $arr = json_decode($accessValue, TRUE);
            if(!empty($arr['access_token'])){
                $access_token = $arr['access_token'];
            }
        }else{
            $access_token = self::get_access_token_by_weixin();
        }
        return $access_token;
    }
    
    /**
     * @info 调用微信接口获取全局access_token
     * @author Jackie Yang
     */
    public static function get_access_token_by_weixin(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?';
        $url .= 'grant_type=client_credential&';
        $url .= 'appid='.APPID;
        $url .= '&secret='.APPSECRET;
        $info = self::http_post($url, '');
        if($info != FALSE){
            $arr = json_decode($info,true); 
            if(empty($arr) || in_array('errcode', $arr)){
                framework_static_function::write_log('get_access_token:'.$info,'access_token');
                exit('获取全局access_token失败');
            }
            //将access_token保存在磁盘中，防止多次调用
            file_put_contents(ACCESSTOKEN_FILE, $info);
            return $arr['access_token'];
        }else{
            framework_static_function::write_log('get_access_token failed.','access_token');
            return FALSE;
        }
    }

    /**
     * @info 微信头像换图
     * @author Jackie Yang
     * @date 20140628
     * @url   头像地址
     * @i  头像大小  0(640) 46 64 96 132
     */
    public static function headimg($url,$i=46){
        if(mb_substr($url, -1,1,'utf-8') != '0'){
            return $url;
        }
        $ur = mb_substr($url, 0, mb_strlen($url)-1,'utf-8');
        if($i==46){
            return $ur.'46';
        }elseif($i==64){
            return $ur.'64';
        }elseif($i==96){
            return $ur.'96';
        }elseif($i==132){
            return $ur.'132';
        }else{
            return $url;
        }
    }
    
    /**
     * curl post 
     * @author Jackie Yang
     */
    public static function http_post($url,$postData){
        try{
             $ch = curl_init(); 
             curl_setopt($ch, CURLOPT_URL, $url); 
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
             curl_setopt($ch, CURLOPT_POST,TRUE); 
             curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); 
             curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//禁止直接显示获取的内容 重要
             if(strpos($url,'https') !== false) {
             	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
             	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //
             }             
             $result = curl_exec($ch); 
             $info = curl_getinfo($ch); 
             //$re = json_decode($result, true); 
             curl_close($ch) ; 
             if(empty($info) || $info['http_code'] != '200') {
                 framework_static_function::write_log('http_post failed'.$info['http_code'],'weixin_curl');
                 return FALSE; 
             } 
             return $result; 
         }catch(Exception $e){
             framework_static_function::write_log('http_post exception:'.$e->getMessage(),'weixin_curl');
             return FALSE;  
         } 
    }
    /**
     * 将用户上传的图片保存到weixin_image_message表
     * @return number
     */
    public static function get_img_msg() {
    	$msg_data = array();
    	$msg_id = 0;
    	if(self::$postDataObj->MsgType == 'image') {
    		$msg_data['from_user'] = self::$fromUserName;
    		$msg_data['create_time'] = date("Y-m-d H:i:s",intval(self::$postDataObj->CreateTime));
    		$msg_data['picurl'] = self::$postDataObj->PicUrl;
    		$msg_data['mediaId'] = self::$postDataObj->MediaId;
    		$msg_data['msgId'] = self::$postDataObj->MsgId;
    		
    		$msg_id = model_message::add_img_msg($msg_data);
    		//将图片资源保存到本地，不再传递到日照后台系统。
    		/*if($msg_id > 0) {
    			$result = array(
    					'fromuser' => $msg_data['from_user'],
    					'msgtype' => 'image',
    					'picurl' => $msg_data['picurl']
    			);
    		} else {
    			$result = array();
    		}*/
    	}
    	/* else {
    		$result = array();
    	}
    	
    	return $result;*/
    	return $msg_id;
    }
    /**
     * 获取消息文本
     * @return string $resultStr 消息内容
     */
	public static function get_text_msg() {
    	$resultStr = '';
    	if(!empty(self::$postDataObj)){
    		if(self::$postDataObj->MsgType == 'text') {
    			$resultStr = self::$postDataObj->Content;    			
    		}
    	}
    	return $resultStr;
    }
    /**
     * 获取消息来源用户
     * @return string $resultStr 消息内容
     */
	public static function get_from_username() {
    	$openid = '';
    	if(!empty(self::$postDataObj)){
    		$openid = self::$postDataObj -> FromUserName;
    	}
    	return $openid;
    }
    /**
     * 
     * 获取发送给微信的消息报文（格式化消息报文）
     * @param string $textTpl 消息模板
     * @param string $msgType 消息类型  如“text”
     * @param string $contentStr 消息正文
     */
    public static function get_msg_content($textTpl,$msgType, $contentStr) {
    	return sprintf($textTpl, self::$fromUserName, self::$toUserName, time(), $msgType, $contentStr);
    }
}